package com.tuyan.aixiang.activity.web;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;

import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tuyan.aixiang.common.BaseActivity;
import com.tuyan.aixiang.util.ToastUtil;

import androidx.annotation.Nullable;

public class AxWebChromeClient extends WebChromeClient {

    private BaseActivity activity;

    private ValueCallback<Uri[]> vcUploadCallback;

    private static final int REQUEST_CODE_FILE_CHOOSER = 8088;


    public AxWebChromeClient(BaseActivity activity) {
        this.activity = activity;
    }

    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {

        vcUploadCallback = valueCallback;
        Intent intent = fileChooserParams.createIntent();
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            activity.startActivityForResult(intent, REQUEST_CODE_FILE_CHOOSER);
        } catch (ActivityNotFoundException e) {
            vcUploadCallback = null;
            ToastUtil.makeShort("无法打开文件管理器");
            return false;
        }
        return true;
//        return super.onShowFileChooser(webView, valueCallback, fileChooserParams);
    }

    @Override
    public void onProgressChanged(WebView webView, int i) {
        super.onProgressChanged(webView, i);
        if (i == 100) {
            activity.hideLoading();
        }
    }


    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_FILE_CHOOSER:
                    if (null != vcUploadCallback) {
                        vcUploadCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                        vcUploadCallback = null;
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case REQUEST_CODE_FILE_CHOOSER:
                    this.vcUploadCallback.onReceiveValue(null);
                    this.vcUploadCallback = null;
                    break;
                default:
                    break;
            }
        }
    }
}
